package work.chief.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import work.chief.backend.common.BaseResponse;
import work.chief.backend.common.ResultUtils;
import work.chief.backend.controller.request.user.UserLoginRequest;
import work.chief.backend.controller.request.user.UserRegisterRequest;
import work.chief.backend.domain.User;
import work.chief.backend.domain.UserPojo;
import work.chief.backend.domain.constant.UserConstant;
import work.chief.backend.exception.BusinessException;
import work.chief.backend.exception.model.ErrorCode;
import work.chief.backend.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static work.chief.backend.domain.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 */
//@CrossOrigin(allowCredentials = "true")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/preRegister/{userAccount}")
    public BaseResponse<Long> checkAccount(@PathVariable String userAccount) {
        System.out.println("controller:::"+userAccount);
        long result = userService.userRegister(userAccount);
        System.out.println(result);
        if (result == 1) {
            return ResultUtils.error(1, "账号已存在");
        }
        return ResultUtils.success(null);

    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userName = userRegisterRequest.getUserName();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return ResultUtils.error(0, "用户名或密码为空");
        }
        long result = userService.userRegister(userName, userAccount, userPassword, checkPassword, UserConstant.DEFAULT_ROLE);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        System.out.println(userAccount + userPassword);
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);

        System.out.println("查看："+request.getSession().getAttribute(USER_LOGIN_STATE));
        System.out.println(request.getSession().getId());
        String id = request.getSession().getId();

        if (user != null) {
//            return ResultUtils.success(user);
            return ResultUtils.success(user);
        }
        return ResultUtils.error(1,"账号或密码错误");
    }

    /**
     * 用户注销
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        System.out.println("退出登录");
        System.out.println(request.getSession().getAttribute(USER_LOGIN_STATE));
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

//    /**
//     * 获取当前登录用户
//     */
//    @GetMapping("/get/login")
//    public BaseResponse<UserVO> getLoginUser(HttpServletRequest request) {
//        User user = userService.getLoginUser(request);
//        UserVO userVO = new UserVO();
//        BeanUtils.copyProperties(user, userVO);
//        return ResultUtils.success(userVO);
//    }
//
//
//    /**
//     * 创建用户
//     */
//    @PostMapping("/add")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
//        if (userAddRequest == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User user = new User();
//        BeanUtils.copyProperties(userAddRequest, user);
//        boolean result = userService.save(user);
//        if (!result) {
//            throw new BusinessException(ErrorCode.OPERATION_ERROR);
//        }
//        return ResultUtils.success(user.getId());
//    }
//
//    /**
//     * 删除用户
//     */
//    @PostMapping("/delete")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
//        if (deleteRequest == null || deleteRequest.getId() <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        boolean b = userService.removeById(deleteRequest.getId());
//        return ResultUtils.success(b);
//    }
//
//    /**
//     * 更新用户
//     */
//    @PostMapping("/update")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
//            HttpServletRequest request) {
//        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User user = new User();
//        BeanUtils.copyProperties(userUpdateRequest, user);
//        boolean result = userService.updateById(user);
//        return ResultUtils.success(result);
//    }
//
//    /**
//     * 根据 id 获取用户
//     */
//    @GetMapping("/get")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<UserVO> getUserById(int id, HttpServletRequest request) {
//        if (id <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User user = userService.getById(id);
//        UserVO userVO = new UserVO();
//        BeanUtils.copyProperties(user, userVO);
//        return ResultUtils.success(userVO);
//    }
//
//    /**
//     * 获取用户列表
//     */
//    @GetMapping("/list")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<List<UserVO>> listUser(UserQueryRequest userQueryRequest, HttpServletRequest request) {
//        User userQuery = new User();
//        if (userQueryRequest != null) {
//            BeanUtils.copyProperties(userQueryRequest, userQuery);
//        }
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
//        List<User> userList = userService.list(queryWrapper);
//        List<UserVO> userVOList = userList.stream().map(user -> {
//            UserVO userVO = new UserVO();
//            BeanUtils.copyProperties(user, userVO);
//            return userVO;
//        }).collect(Collectors.toList());
//        return ResultUtils.success(userVOList);
//    }
//
//    /**
//     * 分页获取用户列表
//     */
//    @GetMapping("/list/page")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Page<UserVO>> listUserByPage(UserQueryRequest userQueryRequest, HttpServletRequest request) {
//        long current = 1;
//        long size = 10;
//        User userQuery = new User();
//        if (userQueryRequest != null) {
//            BeanUtils.copyProperties(userQueryRequest, userQuery);
//            current = userQueryRequest.getCurrent();
//            size = userQueryRequest.getPageSize();
//        }
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
//        Page<User> userPage = userService.page(new Page<>(current, size), queryWrapper);
//        Page<UserVO> userVOPage = new PageDTO<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
//        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
//            UserVO userVO = new UserVO();
//            BeanUtils.copyProperties(user, userVO);
//            return userVO;
//        }).collect(Collectors.toList());
//        userVOPage.setRecords(userVOList);
//        return ResultUtils.success(userVOPage);
//    }

}
